package edu.nf.ch05.service;

import edu.nf.ch05.entity.User;
import edu.nf.ch05.mapper.UserMapper;
import edu.nf.ch05.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.Map;

/**
 * @author wangl
 * @date 2025/4/23
 */
public class UserService {

    public List<User> listUsers(Map<String, Object> params) {
        try(SqlSession session = MybatisUtils.getSqlSession()) {
            return session.getMapper(UserMapper.class)
                    .listUsers(params);
        }
    }

    public List<User> listUsersById(List<Integer> ids) {
        try(SqlSession session = MybatisUtils.getSqlSession()) {
            return session.getMapper(UserMapper.class)
                    .listUsersById(ids);
        }
    }

    public void update(User user) {
        try(SqlSession session = MybatisUtils.getSqlSession()) {
            session.getMapper(UserMapper.class).update(user);
        }
    }

    public void batchInsert(List<User> users) {
        SqlSession session = MybatisUtils.getSqlSession(false);
        try {
            UserMapper mapper = session.getMapper(UserMapper.class);
            mapper.batchInsert(users);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            throw new RuntimeException(e);
        } finally {
            session.close();
        }

    }

    public void batchDelete(List<Integer> ids) {
        SqlSession session = MybatisUtils.getSqlSession(false);
        try {
            UserMapper mapper = session.getMapper(UserMapper.class);
            mapper.batchDelete(ids);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            throw new RuntimeException(e);
        } finally {
            session.close();
        }

    }
}